1092. Shortest Common Supersequence - LeetCode Solution


Dynamic Programming

Python Code:

class Solution:
    def shortestCommonSupersequence(self, a: str, b: str) -> str:
        t = []


        for i in  range(len(a)+1):
            l = []
            for j in range(len(b)+1):
                l.append(0)
            t.append(l)


        for i in range(1, len(a)+1, 1):
            for j in range(1,len(b)+1, 1):
                if a[i - 1] == b[j - 1]:
                    t[i][j] = 1 + t[i-1][j-1]



                else:
                    t[i][j]  = max(t[i-1][j], t[i][j-1])


        i = len(a)
        j = len(b)

        string = ""

        while i>0 and j > 0:
            if a[i-1] == b[j-1]:
                string+= a[i-1]
                i-=1
                j-=1
            else:
                if t[i][j-1] > t[i-1][j]:
                    string+= b[j-1]

                    j-=1
                else:
                    string+= a[i-1]
                    i-=1


        while i>0:
            string += a[i-1]
            i-=1

        while j>0:
            string += b[j-1]
            j-=1



        return string[::-1]


Comments

Submit
0 Comments
More Questions

1647D - Madoka and the Best School in Russia
1208A - XORinacci
1539B - Love Song
22B - Bargaining Table
1490B - Balanced Remainders
264A - Escape from Stones
1506A - Strange Table
456A - Laptops
855B - Marvolo Gaunt's Ring
1454A - Special Permutation
1359A - Berland Poker
459A - Pashmak and Garden
1327B - Princesses and Princes
1450F - The Struggling Contestant
1399B - Gifts Fixing
1138A - Sushi for Two
982C - Cut 'em all
931A - Friends Meeting
1594A - Consecutive Sum Riddle
1466A - Bovine Dilemma
454A - Little Pony and Crystal Mine
2A - Winner
1622B - Berland Music
1139B - Chocolates
1371A - Magical Sticks
1253A - Single Push
706B - Interesting drink
1265A - Beautiful String
214A - System of Equations
287A - IQ Test